package com.tg.base.concurrent.future;

import com.google.common.collect.Lists;

import java.util.ArrayList;
import java.util.concurrent.*;

/**
 * 验证FutureTask取消机制
 * 应遵循Thread的中断机制
 */
public class FutureTaskCancel {

    /**
     * 控制是否可以中断慢操作
     */
    private volatile static boolean beInterrupted = false;

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        Executor executor = Executors.newSingleThreadExecutor();

        FutureTask<Integer> task = new FutureTask<Integer>(() -> slowAction(beInterrupted));
        executor.execute(task);

        //先挂起3秒，否则会直接取消任务，无法进入慢操作
        TimeUnit.SECONDS.sleep(3);

        task.cancel(true);

        //当取消任务后，再次执行task.get()会报错java.util.concurrent.CancellationException
        System.out.println("已取消任务，结果：" + task.get());
    }

    /**
     * 慢操作，同时
     */
    private static int slowAction(boolean beInterrupted) {
        ArrayList<Integer> objects = Lists.newArrayList();
        ArrayList<Integer> results = Lists.newArrayList();
        for (int i = 0; i < 100000; i++) {

            if (beInterrupted && Thread.currentThread().isInterrupted()) {
                System.out.println("中断退出");
                return 1;
            }

            objects.add(i);
            int t = 5 * i;
            if (objects.contains(t)) {
                results.add(t);
            }
            System.out.println(i);
        }


        return 0;
    }
}
